package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @ClassName: UserServiceImpl
 * @Author: YuanDing
 * @Date: 2024/2/4 20:36
 * @Description:
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String code = userLoginDTO.getCode();
        String openId = getOpenId(code);
        if (openId != null) {
            UserLoginVO userLoginVO = new UserLoginVO();
            User user =  userMapper.selectUserByOpenId(openId);
            if (user == null) {
                user = User.builder()
                        .openid(openId)
                        .createTime(LocalDateTime.now())
                        .build();
                userMapper.insertUser(user);
            }
            userLoginVO.setId(user.getId());
            userLoginVO.setOpenid(openId);

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("userId" , user.getId());
            String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), hashMap);

            userLoginVO.setToken(jwt);
            return userLoginVO;
        } else {
            throw new LoginFailedException("登录失败");
        }
    }

    private String getOpenId(String code) {
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("appid" , weChatProperties.getAppid());
        paramsMap.put("secret" , weChatProperties.getSecret());
        paramsMap.put("js_code" , code);
        paramsMap.put("grant_type" , "authorization_code");
        String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session" , paramsMap);
        return JSON.parseObject(result).getString("openid");
    }
}
